package com.heo.music.player.config.swagger;

import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.Optional;

import static springfox.documentation.schema.Annotations.findPropertyAnnotation;
import static springfox.documentation.swagger.schema.ApiModelProperties.findApiModePropertyAnnotation;

/**
 * @author 星天无极
 * @create 2022-05-18 10:32
 **/
@Component
@Slf4j
@ConditionalOnProperty(
    name = {"knife4j.enable"},
    havingValue = "true"
)
public class CustomModelPropertyBuilderPlugin implements ModelPropertyBuilderPlugin {

    @Override
    public boolean supports(@NonNull DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }

    @Override
    public void apply(ModelPropertyContext context) {

        ApiModelProperty apiModelProperty = null;

        Optional<AnnotatedElement> annotatedElementOptional = context.getAnnotatedElement();
        if (annotatedElementOptional.isPresent()) {
            AnnotatedElement annotatedElement = annotatedElementOptional.get();
            Optional<ApiModelProperty> apiModelPropertyOptional = findApiModePropertyAnnotation(annotatedElement);
            if (apiModelPropertyOptional.isPresent()) {
                apiModelProperty = apiModelPropertyOptional.get();
            }
        }

        Optional<BeanPropertyDefinition> beanPropertyDefinitionOptional = context.getBeanPropertyDefinition();
        if (beanPropertyDefinitionOptional.isPresent()) {
            BeanPropertyDefinition beanPropertyDefinition = beanPropertyDefinitionOptional.get();
            Optional<ApiModelProperty> apiModelPropertyOptional = findPropertyAnnotation(beanPropertyDefinition, ApiModelProperty.class);
            if (apiModelPropertyOptional.isPresent()) {
                apiModelProperty = apiModelPropertyOptional.get();
            }
        }

        Optional<BeanPropertyDefinition> beanPropertyDefinitionOpt = context.getBeanPropertyDefinition();
        if (apiModelProperty != null && beanPropertyDefinitionOpt.isPresent()) {
            if (apiModelProperty.position() != 0) {
                return;
            }

            BeanPropertyDefinition beanPropertyDefinition = beanPropertyDefinitionOpt.get();
            AnnotatedField field = beanPropertyDefinition.getField();

            Class<?> clazz = field.getDeclaringClass();
            Field[] declaredFields = clazz.getDeclaredFields();
            Field declaredField;

            try {
                declaredField = clazz.getDeclaredField(field.getName());
            } catch (NoSuchFieldException | SecurityException e) {
                log.error("", e);
                return;
            }
            if (declaredField.isAnnotationPresent(NotNull.class)
                ||
                declaredField.isAnnotationPresent(NotEmpty.class)) {
                context.getBuilder().required(true);
            }
            int indexOf = -1;
            for (int i = 0; i < declaredFields.length; i++) {
                if (Objects.equals(declaredFields[i], declaredField)) {
                    indexOf = i;
                    break;
                }
            }
            if (indexOf != -1) {
                context.getBuilder().position(indexOf + 10);
            }
        }

    }

}
